package cn.hchaojie.ssm.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hchaojie.ssm.domain.AjaxResponse;
import cn.hchaojie.ssm.domain.Post;
import cn.hchaojie.ssm.mapper.PostMapper;

@Service
public class PostService {
	@Autowired
	PostMapper mapper = null;
	
	public List<Post> findAll() {
		List<Post> all = mapper.findAll();
		
//		if (true) {
//			throw new RuntimeException("服务器出错！");
//		}
		
		return all;
	}
	
	/**
	 * 
	 * @param page - 第几页，从1开始
	 * @param size
	 * @return
	 */
	public AjaxResponse<Post> searchPage(String title, Integer cid, Date created, int page, int size) {
		if (title != null && title.length() != 0) {
			title = "%" + title + "%";
		}
		
		// 当前页数据
		List<Post> all = mapper.searchPage(title, created, cid,
				(page - 1) * size, size);

		// 一共有多少条数据
		int count =  mapper.searchCount(title, created, cid);

		AjaxResponse<Post> result = new AjaxResponse<>();
		result.setData(all);
		result.setCount(count);
		
		return result;
	}
	
	public void deleteBatch(String[] ids) {
		mapper.deleteBatch(ids);
	}

	public void insert(Post p) {
		mapper.insert(p);
	}

	public Post getById(int id) {
		return mapper.getById(id);
	}
	
	public Post getByIdWithCategory(int id) {
		return mapper.getByIdWithCategory(id);
	}

	public void deleteById(int id) {
		mapper.deleteById(id);
	}

	public void update(int id, Post p) {
		mapper.update(id, p);
	}

	public List<Post> search(Post p, Integer page, Integer size) {
		if (p.getTitle() != null && p.getTitle().length() != 0) {
			p.setTitle("%" + p.getTitle() + "%");
		}
		
		Integer cid = p.getCategory() != null ? p.getCategory().getId() : null;
		return mapper.searchPage(p.getTitle(), p.getCreated(), cid, page, size);
	}
}
